/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package drivemachine.data2;

import java.util.*;

/**
 *
 * @author positron
 */
//public enum Diff {Self, Sub, Date};
public class CompareEntry extends Entry<Boolean> {

	public String comment = null;
	private FolderEntry older, newer;

	public CompareEntry(FolderEntry f1, FolderEntry f2) {
		super(f1!=null?f1.getFileName():f2.getFileName());
		init(f1,f2);
	}
	public CompareEntry(CompareEntry parent, FolderEntry f1, FolderEntry f2) {
		super(parent, f1!=null?f1.getFileName():f2.getFileName());
		init(f1,f2);
	}

	private void init(FolderEntry oldEntry, FolderEntry newEntry) {
		older = oldEntry;
		newer = newEntry;
		if(oldEntry!=null && newEntry!=null) {
			assert oldEntry.name.equals(newEntry.name) : "Cannot create compareentry from entries with different names";
			selfsize = newEntry.getSelfSize() - oldEntry.getSelfSize();
		} else
		if(oldEntry==null) {
			comment = "new";
			selfsize = newEntry.getFullSize();
		} else
		if(newEntry==null) {
			comment = "deleted";
			selfsize = -oldEntry.getFullSize();
		}
	}

	public void traverse() {
		if(older==null || newer==null) return;
		Map<String, FolderEntry> newerNames = new HashMap<>();
		for( Entry nn: newer.children) newerNames.put(nn.getFileName(), (FolderEntry)nn);
		Map<String, FolderEntry> olderNames = new HashMap<>();
		for( Entry nn: older.children) olderNames.put(nn.getFileName(), (FolderEntry)nn);

		for( String f: olderNames.keySet() ) {
			FolderEntry fo = olderNames.get(f);
			FolderEntry fn = newerNames.get(f);
			if(fn != null) {
				if(fo.getFullSize() != fn.getFullSize()) {
					children.add(new CompareEntry(this, fo, fn));
				}
				newerNames.remove(fn.getFileName());
			} else {
				children.add( new CompareEntry(this, fo, null) );
			}
		}
		for( String f: newerNames.keySet() ) {
			FolderEntry fo = olderNames.get(f);
			FolderEntry fn = newerNames.get(f);
			if(fo==null) {
				children.add( new CompareEntry(this, null, fn) );
			}
		}

		for(Entry c: children) {
			((CompareEntry)c).traverse();
			subsize += c.getFullSize();
		}

		Collections.sort(children);
		Collections.reverse(children);

	}

	@Override
	public String toString() {
		if (selfsize == -1) {
			return super.toString();
		}
		long fs = getFullSize();
		return filename + " (" + (fs > 0 ? "+" : "") + Entry.sizeToString(fs) + ") " + (comment != null ? comment : "");
	}

}
